'use strict';
let registered = null;
var musicList = new Array();
chrome.action.setBadgeText({text: 'new'});
chrome.action.setBadgeBackgroundColor({color: [255, 0, 0, 255]});

// chrome.syncFileSystem.onFileStatusChanged.addListener(function(fileInfo) {
//   if (fileInfo.status === 'synced') {
//     if (fileInfo.direction === 'remote_to_local') {
//       if (fileInfo.action === 'added') {
//         db.add(fileInfo.fileEntry);
//       } else if (fileInfo.action === 'deleted') {
//         db.remove(fileInfo.fileEntry);
//       }
//     }
//   }
// });





function CreateMenu(){
    chrome.contextMenus.create({
        title: '音乐播放',
        id: 'playMenu',
        contexts: ['all'],
        // parentId: '10',
        type: "normal" // "normal", "checkbox", "radio", "separator"
        }, () => {
            console.log('playMenus are created.');
    });
    chrome.contextMenus.create({
            title: '播放',
            id: 'playSong',
            contexts: ['all'],
            parentId: 'playMenu',
            type: "normal" // "normal", "checkbox", "radio", "separator"
        }, () => {
            console.log('playSong are created.');
    });
    chrome.contextMenus.create({
            title: '上一曲(Alt+P)',
            id: 'prevSong',
            parentId: 'playMenu',
            contexts: ['all'],
            type: "normal" // "normal", "checkbox", "radio", "separator"
        }, () => {
        console.log('prevSong are created.');
    });

    chrome.contextMenus.create({
            title: '下一曲(Alt+N)',
            id: 'nextSong',
            contexts: ['all'],
            parentId: 'playMenu',
            type: "normal" // "normal", "checkbox", "radio", "separator"
        }, () => {
        console.log('nextSong are created.');
    });


    chrome.contextMenus.create({
            title: '暂停',
            id: 'pauseSong',
            parentId: 'playMenu',
            contexts: ['all'],
            type: "normal" // "normal", "checkbox", "radio", "separator"
        }, () => {
        console.log('pauseMenus are created.');
    });
}

function GetMyMusicList(){
    fetch('http://localhost:1987/getMyMusic', {
        method: 'GET', 
        headers: {
            'Content-Type': 'application/json', 
        }
    })
    .then(response => response.json())  // 将响应体解析为JSON
    .then( data => {
        let {code,msg,songs} = data;
        console.log(code,msg,songs)
        if (code == 200){
            for(var i = 0;i< songs.length;i++){
                var song = songs[i];
                musicList.push(song);
            }
        }
    })
    .catch((error) => {
        console.log("音乐获取失败");
    });
}

chrome.runtime.onMessage.addListener(handleMessage); 


chrome.commands.onCommand.addListener((command) => {
    console.log(command);

    chrome.windows.getCurrent(function (tab){
        console.log(tab.id);
        chrome.tabs.sendMessage(tab.id,{greeting:command,from:"background",eventType:"command"},function(response) {
            console.log('background get response:',response);
        });
        chrome.runtime.sendMessage( {greeting:command,from:"background",eventType:"command"},function(response) {
            console.log('background get response:',response);
        });

    })
   
});

chrome.tabs.onUpdated.addListener(
    function(tabId, changeInfo,tab) {
        console.log("chrome.tabs.onUpdated",tabId);
    }
)


function selectionOnClick(){
    console.log("selectionOnClick");
}



chrome.runtime.onMessageExternal.addListener(
    function(request, sender, sendResponse) {
        console.log(request); // 发送的消息
        console.log(sender); // 发送者的信息，tabs相关信息
        sendResponse(sender);// 这里将tab信息发送给发送者
});


console.log(chrome.tabs);

console.log(chrome.tabs.TabStatus);


    


// 监听右键菜单被点击事件
chrome.contextMenus.onClicked.addListener((menuInfo, tabInfo) => {
    // 菜单信息，具体内容请自行查看调试窗口的调试日志
    console.log("menuInfo:", JSON.stringify(menuInfo))
    // 页面信息，具体内容请自行查看调试窗口的调试日志
    console.log("tabInfo:", JSON.stringify(tabInfo))
    console.log("windowId:", tabInfo.mutedInfo.windowId);
    
    chrome.tabs.query({
        active: true, currentWindow: true
    }, (tabs) => {
        // 页签信息，具体内容请自行查看调试窗口的调试日志
        console.log("tabs:", JSON.stringify(tabs))
        for (var i = tabs.length - 1; i >= 0; i--) {
            console.log(tabs[i]);

        }
    })

    chrome.tabs.sendMessage(tabInfo.id,{greeting:menuInfo,from:"background",eventType:"MenuClick"},function(response) {
        console.log('background get response:',response);
    });

    
    

    
});



chrome.action.onClicked.addListener(function (tab) {
    console.log("chrome.action.onClicked");
    // 设置标题
    chrome.action.setTitle({ tabId: tab.id, title: "You are on tab:" + tab.id });
    // 设置文字
    chrome.action.setBadgeText({ text: "ON" });
    chrome.action.show(tabId) 
    chrome.pageAction.show(tabId) 
    chrome.scripting.executeScript({
        target: { tabId: tab.id },
        files: ["js/content.js"]
    });
    const logs = 'chrome.action.onClicked';


    
});



chrome.tabs.onRemoved.addListener(function (tabId, removeInfo) {
    console.log("关闭窗口 tabId: " + tabId);
});


// 窗口移除事件监听
chrome.windows.onRemoved.addListener(function (windowId) {
    console.log("chrome tab remove begin, windowId: " + windowId);
});


chrome.runtime.onSuspendCanceled.addListener(() => {
    console.log("chrome.runtime.onSuspendCanceled");
})

chrome.runtime.onUpdateAvailable.addListener(() => {
    console.log("chrome.runtime.onUpdateAvailable");
})

chrome.runtime.onRestartRequired.addListener(() => {
    console.log("chrome.runtime.onRestartRequired");
})

chrome.runtime.onStartup.addListener(() => {
    console.log("chrome.runtime.onStartup");
})


chrome.runtime.onUserScriptMessage.addListener(() => {
    console.log("onUserScriptMessage");
})

chrome.runtime.onUserScriptConnect.addListener(() => {
    console.log("onUserScriptConnect");
})


chrome.runtime.onConnect.addListener(function(port) {
    console.log(port)
    console.assert(port.name == "yisheng");
    port.onMessage.addListener(function(msg) {
        if (msg.joke == "Knock knock")
            port.postMessage({question: "Who's there?"});
        else if (msg.answer == "Madame")
            port.postMessage({question: "Madame who?"});
        else if (msg.answer == "Madame... Bovary")
            port.postMessage({question: "I don't get it."});
    });
});



// 插件安装监听事件
chrome.runtime.onInstalled.addListener(() => {
    const logs = 'onInstalled';
    
    CreateMenu();
    // console.log(chrome.runtime.getManifest());
    // console.log(chrome.extension);
    // console.log(chrome.runtime.getBackgroundClient);
    // console.log("getPlatformInfo",chrome.runtime.getPlatformInfo);
    // console.log("getURL",chrome.runtime.getURL);
    // console.log("onStartup",chrome.runtime.onStartup);
    // console.log(chrome.runtime);
    chrome.storage.local.clear();
    chrome.storage.sync.clear();
    console.log("发送 ready 信息");
    // GetMyMusicList();
    // chrome.runtime.sendMessage( {greeting:"ready",from:"background"},function(response) {
    //     console.log(chrome.fileSystem);
    //     console.log(response);
    // });
    // chrome.storage.local.set({
    //     "demo": "demo 数据",
    //     "env": "dev"
    // }, function () {
    //     console.log("chrome extension is install.");
    // });
    // The ID of the extension we want to talk to.
    


});

function handleMessage(msg,request,callback) {
    try{
        console.log("handleMessage",msg,request);
        console.log(msg.audio);
        callback(msg);
    }catch (exception) {
        console.log("获取消息失败");
    }
    
}


